<template>
  <div class="my-page-container">
    <fm-nav-bar title="个人中心"></fm-nav-bar>
    <!-- <div class="personal-top">
      <div class="personal-top-left">
        <fm-image :src="require('@/assets/img/avatar-person.png')" />
      </div>
      <div class="personal-top-info">
        <div class="username">{{ userFullName }}</div>
        <div class="light-font">暂无自我介绍</div>
      </div>
      <div class="personal-top-right" @click="show = true">
        <fm-image
          width="20"
          height="20"
          fit="cover"
          :src="require('@/assets/img/person-qrcode.png')"
        />
      </div>
    </div> -->
    <fm-cell-group inset style="margin-top: 12px">
      <fm-cell title="头像" center @click="showAvatar">
        <div class="has-img">
          <!-- <fm-image :src="imageUrl" class="personal-top-left" /> -->
          <img v-if="imageUrl" :src="imageUrl | getAvatar" class="avatar" />
          <div v-else class="avatar avatar-text">
            {{ userFullName | getFamilyName }}
          </div>
          <fm-image class="arrow" fit="cover" :src="require('@/assets/img/arrow-right.png')" />
        </div>
      </fm-cell>
      <fm-cell title="姓名" :value="userFullName"> </fm-cell>
      <fm-cell title="手机" :value="phone"></fm-cell>
      <fm-cell title="邮箱" :value="email"></fm-cell>
      <fm-cell title="公司" :value="userComp"></fm-cell>
      <fm-cell title="部门" :value="userDept"></fm-cell>
      <fm-cell title="我的二维码" @click="show = true" center>
        <div class="has-img">
          <fm-image class="qrcode" fit="cover" :src="require('@/assets/img/person-qrcode.png')" />
          <fm-image class="arrow" fit="cover" :src="require('@/assets/img/arrow-right.png')" />
        </div>
      </fm-cell>

      <!-- <fm-cell title="二维码名片" @click="show = true">
        <template #right-icon>
          <i class="fm-icon fm-icon-qr" scale="3" style="height: 20px; width: 20px"></i>
        </template>
      </fm-cell>
      <fm-cell title="版本信息" value="1.1.0"></fm-cell> -->
    </fm-cell-group>
    <fm-cell-group inset style="margin-top: 24px">
      <fm-cell title="指纹登录" v-if="!disableFinger" center>
        <fm-switch v-model="enableFinger" @change="saveFingerState" />
      </fm-cell>
    </fm-cell-group>
    <div class="version-info">
      <div class="version-number">当前版本V2.0.0</div>
    </div>
    <!-- <fm-cell-group style="margin-top: 14px"
      ><fm-cell @click="gotoChangePass" title="修改密码" is-link></fm-cell
    ></fm-cell-group> -->
    <div class="logout">
      <fm-button type="primary" block color="#ffffff" size="large" @click="logout"
        >退出登录</fm-button
      >
    </div>

    <!-- 二维码展示遮罩层 -->
    <fm-overlay :show="show">
      <fm-nav-bar
        class="qrcode-header"
        title="我的二维码"
        background="#F2F3F4"
        left-arrow
        @click-left="show = false"
      />
      <div class="wrapper">
        <div class="block">
          <div class="block-top">
            <div class="block-top-left">
              <fm-image
                width="65"
                height="65"
                fit="cover"
                :src="require('@/assets/img/avatar-person.png')"
              />
            </div>
            <div class="personal-top-info">
              <div class="username">{{ userFullName }}</div>
              <span class="light-font">{{ email }}</span>
            </div>
          </div>
          <div class="block-bottom">
            <qrcode :value="qrCodeText" :size="200" />
            <div class="blockText">扫一扫，查看我的名片</div>
          </div>
        </div>
      </div>
    </fm-overlay>
    <fm-overlay :show="showPic">
      <fm-nav-bar
        class="qrcode-header"
        title="我的头像"
        background="#F2F3F4"
        left-arrow
        @click-left="showPic = false"
      />
      <div class="profile">
        <fm-image :src="imageUrl | getAvatar" class="profile-img" />
      </div>
    </fm-overlay>
    <tabbar></tabbar>
  </div>
</template>
<script>
import { CellGroup, Cell, Button, NavBar, Overlay, Image, Dialog, Toast } from 'fawkes-mobile-lib'
import { STATUS_BAR_HEIGHT } from '@/store/State/stateTypes'
import { loginOut } from '@/api/app'
import { getUser } from '@/api/user'
import Qrcode from '@/components/qrcode'
import { eventBackButton, exitApp } from '@/utils/app'
import { IS_LOGIN } from '@/store/Mutation/mutationTypes'
import tabbar from '@/modules/Tabbar/index'
export default {
  name: 'PersonalCenter',
  components: {
    tabbar,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [NavBar.name]: NavBar,
    [Overlay.name]: Overlay,
    [Image.name]: Image,
    [Toast.name]: Toast,
    Qrcode,
  },
  data() {
    return {
      disableFinger: true,
      enableFinger: false,
      userFullName: '',
      userDept: '',
      userComp: '',
      phone: '',
      show: false,
      showPic: false,
      email: '',
      imageUrl: '',
      // qrcode: "https://fawkes.cybereng.com/",
      loading: false,
    }
  },
  filters: {
    getFamilyName(value) {
      return value?.substr(0, 1)
    },
    getAvatar(val) {
      return `${process.env.VUE_APP_BASE_URL}/sys-storage/download_image?f8s=${val}`
    },
  },
  computed: {
    statusBarHeight() {
      return this.$store.state[STATUS_BAR_HEIGHT]
    },
    // 可微信扫描查看具体展示的信息
    qrCodeText() {
      let QRText = `BEGIN:VCARD"
      FN: ${this.userFullName}
      TEL: ${this.phone}
      ADR;WORK:浙江省杭州市余杭区高教路201号
      EMAIL;INTERNET,HOME: ${this.email}
      ORG: ${this.userDept};
      END:VCARD`
      return QRText
    },
  },
  watch: {
    show(newVal) {
      // 处理overlay响应物理返回键
      if (newVal) {
        document.removeEventListener('backbutton', eventBackButton, false)
        document.removeEventListener('backbutton', exitApp, false)
        document.addEventListener('backbutton', this.closeOverlay, false)
      } else {
        document.removeEventListener('backbutton', this.closeOverlay, false)
        document.addEventListener('backbutton', eventBackButton, false)
      }
    },
  },
  beforeMount() {},
  mounted() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    })
    // 页面激活时移除默认的返回上一级路由处理事件，设置退出应用事件
    document.removeEventListener('backbutton', this.$back, false)
    document.addEventListener('backbutton', eventBackButton, false)
    this.getUserInfo()
    this.userFullName = this.$storage.get('userFullname')
    this.fingerPermission()
    this.enableFinger = this.$storage.get('enableFinger') === 'true' ? true : false
  },
  deactivated() {
    // 页面隐藏时移除退出应用事件，恢复默认的返回上一级路由的处理事件
    document.removeEventListener('backbutton', eventBackButton, false)
    document.removeEventListener('backbutton', exitApp, false)
    document.addEventListener('backbutton', this.$back, false)
  },
  methods: {
    logout() {
      document.removeEventListener('backbutton', eventBackButton, false)
      document.removeEventListener('backbutton', exitApp, false)
      Dialog.alert({
        title: '确认退出登录？',
        theme: 'default',
        confirmButtonColor: '#4545D1',
        cancelButtonColor: '#353535',
        showCancelButton: true,
      })
        .then(() => {
          loginOut()
            .then((res) => {
              if (res.status) {
                this.userFullName = ''
                this.phone = ''
                this.email = ''
                this.userDept = ''
                this.userComp = ''
                // 清除keep-alive缓存
                // this.removeKeepAliveCache()
                this.$store.commit(IS_LOGIN, false)
                this.$storage.remove('access_token')
                this.$storage.remove('langList')
                this.$router.push('/login')
              }
            })
            .catch(() => {})
        })
        .catch(() => {
          // 移除dialog绑定的回退事件
          document.removeEventListener('backbutton', this.$back, false)
          document.addEventListener('backbutton', eventBackButton, false)
        })
    },
    saveFingerState(val) {
      if (!val) {
        this.$storage.set('enableFinger', val)
      } else {
        Fingerprint.show(
          {
            clientId: 'fawkes', //Android: Used for encryption. iOS: used for dialogue if no `localizedReason` is given.
            clientSecret: 'fawkes_secret', //Necessary for Android encrpytion of keys. Use random secret key.
            title: '指纹登录验证',
            disableBackup: true,
            cancelButtonTitle: '取消',
          },
          () => {
            this.$storage.set('enableFinger', val)
          },
          (err) => {
            this.enableFinger = false
          }
        )
      }
    },
    fingerPermission() {
      Fingerprint.isAvailable(
        (result) => {
          this.disableFinger = false
        },
        (message) => {
          this.disableFinger = true
        }
      )
    },
    getUserInfo() {
      let name = this.$storage.get('username')
      let params = {
        userName: name,
      }
      getUser(params)
        .then((res) => {
          this.phone = res.data.phone
          this.email = res.data.email
          this.userDept = res.data.orgList[0]?.entName || '暂无归属'
          this.userComp = res.data.orgList[0]?.parentName || '暂无归属'
          this.imageUrl = res.data.avatarToken
          console.log(this.imageUrl)
          // (process.env.NODE_ENV == 'development' ? '/api' : '../api') +
          // '/sys-storage/download_image?f8s=' +
          // res.data.avatarToken
        })
        .finally(() => {
          Toast.clear()
        })
    },
    gotoChangePass() {
      this.$router.push('/change')
    },
    closeOverlay() {
      this.show = false
    },
    removeKeepAliveCache() {
      if (this.$vnode.parent) {
        let keys = this.$vnode.parent.componentInstance.keys
        let l = keys.length
        for (let i = 0; i < l; i++) {
          this.removeKeepAliveCacheForVueInstance(keys[0], keys)
        }
      }
    },
    removeKeepAliveCacheForVueInstance(item, keys) {
      let key = item
      if (this.$vnode.parent) {
        let cache = this.$vnode.parent.componentInstance.cache
        if (cache[key]) {
          cache[key].componentInstance.$destroy()
          delete cache[key]
          let index = keys.indexOf(key)
          if (index > -1) {
            keys.splice(index, 1)
          }
        }
      }
    },
    showAvatar() {
      if (this.imageUrl) {
        this.showPic = true
      } else {
        this.$toast('未上传头像，无法查看！')
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.fm-cell {
  min-height: 78px !important;
}
/deep/.fm-cell__title {
  font-size: 28px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #15171a;
  line-height: 40px;
}
/deep/.fm-cell__value {
  font-size: 28px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #727478;
  line-height: 40px;
}
/deep/.fm-cell::after {
  right: 0;
}
.has-img {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.my-page-container {
  background-color: #f2f3f4;
  height: calc(100% - 50px);
}
.personal-top {
  padding: 0;
  width: 100%;
  height: 234px;
  background: rgba(255, 255, 255, 1);
  display: flex;
  border-radius: 0 0 16px 16px;
}
.personal-top-left {
  width: 80px;
  height: 80px;
  border-radius: 16px;
}
.personal-top-info {
  // padding: 40px 0 40px 30px;
  margin-top: 84px;
  margin-left: 24px;
  flex: 1;

  .username {
    font-size: 32px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1d2541;
  }
  .light-font {
    font-size: 28px;
    margin-top: 44px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #818595;
  }
}

.qrcode {
  width: 40px;
  height: 40px;
}
.arrow {
  width: 48px;
  height: 48px;
  margin-left: 16px;
}
.personal-top-right {
  width: 40px;
  height: 40px;
  margin-top: 61px;
  margin-right: 30px;
}
/deep/ .fm-button--primary {
  color: #f75355 !important;
  font-weight: 400;
  font-size: 32px;
  height: 108px;
  border-radius: 16px;
}
// /deep/ .fm-cell {
//   font-size: 32px;
//   font-weight: 400;
//   color: #999999;
//   padding: 26px 32px;
// }
// /deep/ .fm-cell__value {
//   font-size: 32px;
//   font-family: PingFangSC-Regular, PingFang SC;
//   font-weight: 400;
//   color: #555555;
// }
.version-info {
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.version-number {
  font-size: 28px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #b5b9be;
  line-height: 40px;
}
/deep/ .fm-overlay {
  background-color: #f2f3f4;
}
.wrapper {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.qrcode-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}
.block {
  width: 686px;
  height: 800px;
  border-radius: 8px;
  background-color: #fff;
}
.block-top {
  display: flex;
}
.block-top-left {
  margin-top: 48px;
  margin-left: 56px;
}
.block-top-info {
  margin-top: 61px;
  margin-left: 24px;
}
.block-bottom {
  margin-top: 56px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 32px;
}
.blockText {
  margin-top: 26px;
  text-align: center;
  font-size: 28px;
  font-weight: 400;
  color: #999999;
}
.fm-icon-qr:before {
  font-size: 2em;
}
.logout {
  width: 686px;
  height: 108px;
  background: #ffffff;
  border-radius: 16px;
  position: fixed;
  bottom: calc(env(safe-area-inset-bottom) + 180px);
  left: 32px;
}
.profile {
  width: 100%;
  height: 100%;
  background: #000;
  display: flex;
  justify-content: center;
  align-items: center;
  .profile-img {
    width: 100%;
  }
}

.avatar {
  width: 80px;
  height: 80px;
  border: 2px solid #fff;
  border-radius: 50%;
  box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.12);
}

.avatar-text {
  line-height: 80px;
  text-align: center;
  font-size: 30px;
  color: #fff;
  background-color: #4545d1;
}
</style>
